<?php

// +----------------------------------------------------------------------
// | ThinkAdmin
// +----------------------------------------------------------------------

use app\admin\service\CaptchaService;
use app\admin\service\NodeService;
use app\admin\service\OplogService;
use library\File;
use think\Console;
use think\Db;
use think\facade\Middleware;
use think\facade\Route;
use think\Request;

if (!function_exists('auth')) {
    /**
     * 节点访问权限检查
     * @param string $node 需要检查的节点
     * @return boolean
     * @throws ReflectionException
     */
    function auth($node)
    {
        return NodeService::checkAuth($node);
    }
}

if (!function_exists('sysdata')) {
    /**
     * JSON 数据读取与存储
     * @param string $name 数据名称
     * @param array|null $value 数据内容
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    function sysdata($name, array $value = null)
    {
        if (is_null($value)) {
            $data = json_decode(Db::name('SystemData')->where(['name' => $name])->value('value'), true);
            return empty($data) ? [] : $data;
        } else {
            return data_save('SystemData', ['name' => $name, 'value' => json_encode($value, JSON_UNESCAPED_UNICODE)], 'name');
        }
    }
}

if (!function_exists('sysoplog')) {
    /**
     * 写入系统日志
     * @param string $action 日志行为
     * @param string $content 日志内容
     * @return boolean
     */
    function sysoplog($action, $content)
    {
        return OplogService::write($action, $content);
    }
}

if (!function_exists('sysqueue')) {
    /**
     * 创建异步处理任务
     * @param string $title 任务名称
     * @param string $loade 执行内容
     * @param integer $later 延时执行时间
     * @param array $data 任务附加数据
     * @param integer $double 任务多开
     * @return boolean
     * @throws \think\Exception
     */
    function sysqueue($title, $loade, $later = 0, $data = [], $double = 1)
    {
        $map = [['title', 'eq', $title], ['status', 'in', [1, 2]]];
        if (empty($double) && Db::name('SystemQueue')->where($map)->count() > 0) {
            throw new \think\Exception('该任务已经创建，请耐心等待处理完成！');
        }
        $result = Db::name('SystemQueue')->insert([
            'title'  => $title, 'preload' => $loade,
            'data'   => json_encode($data, JSON_UNESCAPED_UNICODE),
            'time'   => $later > 0 ? time() + $later : time(),
            'double' => intval($double), 'create_at' => date('Y-m-d H:i:s'),
        ]);
        return $result !== false;
    }
}

if (!function_exists('local_image')) {
    /**
     * 下载远程文件到本地
     * @param string $url 远程图片地址
     * @param boolean $force 是否强制重新下载
     * @param integer $expire 强制本地存储时间
     * @return string
     */
    function local_image($url, $force = false, $expire = 0)
    {
        $result = File::down($url, $force, $expire);
        if (isset($result['url'])) {
            return $result['url'];
        } else {
            return $url;
        }
    }
}

if (!function_exists('base64_image')) {
    /**
     * base64 图片上传接口
     * @param string $content 图片base64内容
     * @param string $dirname 图片存储目录
     * @return string
     */
    function base64_image($content, $dirname = 'base64/')
    {
        try {
            if (preg_match('|^data:image/(.*?);base64,|i', $content)) {
                list($ext, $base) = explode('|||', preg_replace('|^data:image/(.*?);base64,|i', '$1|||', $content));
                $info = File::save($dirname . md5($base) . '.' . (empty($ext) ? 'tmp' : $ext), base64_decode($base));
                return $info['url'];
            } else {
                return $content;
            }
        } catch (\Exception $e) {
            return $content;
        }
    }
}

// 访问权限检查中间键
Middleware::add(function (Request $request, \Closure $next) {
    if (NodeService::forceAuth()) {
        return $next($request);
    } elseif (NodeService::islogin()) {
        return json(['code' => 0, 'msg' => '抱歉，没有访问该操作的权限！']);
    } else {
        return json(['code' => 0, 'msg' => '抱歉，需要登录获取访问权限！', 'url' => url('@admin/login')]);
    }
});

// 注册系统服务指令
Console::addDefaultCommands([
    'app\admin\queue\task\Stop',
    'app\admin\queue\task\Work',
    'app\admin\queue\task\Start',
    'app\admin\queue\task\State',
    'app\admin\queue\task\Query',
    'app\admin\queue\task\Listen',
]);

// ThinkAdmin 图形验证码
Route::get('/think/admin/captcha', function () {
    $image = new CaptchaService();
    return json(['code' => '1', 'info' => '生成验证码', 'data' => [
        'uniqid' => $image->getUniqid(), 'image' => $image->getData()
    ]]);
});

/*base64格式编码转换为图片并保存对应文件夹 */
function base64_image_content($base64_image_content,$path){
    //匹配出图片的格式
    if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){
        $type = $result[2];
        $new_file = $path."/".date('Ymd',time())."/";
        if(!file_exists($new_file)){
            //检查是否有该文件夹，如果没有就创建，并给予最高权限
            mkdirs($new_file, 0700);
        }
        $new_file = $new_file.time().".{$type}";
        if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content)))){
            return '/'.$new_file;
        }else{
            return false;
        }
    }else{
        return false;
    }
}
 
//echo base64_image_content($base64_img,"images");
function mkdirs($dir, $mode = 0777)
{
    if (is_dir($dir) || @mkdir($dir, $mode)) return true;
    if (!mkdirs(dirname($dir), $mode)) return false;
    return @mkdir($dir, $mode);
}

/**
* 邮件发送
* @param $to 接收人
* @param string $subject 邮件标题
* @param string $content 邮件内容(html模板渲染后的内容)
* @throws Exception
* @throws phpmailerException
*/
function send_email($to, $subject='',$content='' , $files){
    require __DIR__.'/../../vendor/phpmailer/phpmailer/class.phpmailer.php';
    require __DIR__.'/../../vendor/phpmailer/phpmailer/class.smtp.php';

    //Create a new PHPMailer instance
    $mail = new PHPMailer;
    //Tell PHPMailer to use SMTP
    $mail->isSMTP();
    //Enable SMTP debugging
    // 0 = off (for production use)
    // 1 = client messages
    // 2 = client and server messages
    $mail->SMTPDebug = 0;

    $mail->CharSet = 'UTF-8';

    //Set the hostname of the mail server
    $mail->Host = 'smtp.qq.com';
    // use
    // $mail->Host = gethostbyname('smtp.gmail.com');
    // if your network does not support SMTP over IPv6
    //Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
    $mail->Port = 465;
    //Set the encryption system to use - ssl (deprecated) or tls
    $mail->SMTPSecure = 'ssl';
    //Whether to use SMTP authentication
    $mail->SMTPAuth = true;
    //Username to use for SMTP authentication - use full email address for gmail
    $mail->Username = "80392625@qq.com";
    //Password to use for SMTP authentication
    $mail->Password = "jvhpbjfjdzkdcafi";
    //Set who the message is to be sent from
    $mail->setFrom('80392625@qq.com', 'OA系统'); //发件人信息
    //Set an alternative reply-to address
    //$mail->addReplyTo('replyto@example.com', 'First Last');
    //Set who the message is to be sent to


    if(is_array($to) && count($to)>0 ){
        foreach ($to as $key => $v) {
            $mail->addAddress($v);
        }
    }else{
        if($to !=''){
            $mail->addAddress($to);
        }
    }
    
    //Set the subject line
    $mail->Subject = 'PHPMailer GMail SMTP test';
    //Read an HTML message body from an external file, convert referenced images to embedded,

    $mail->isHTML(true);

    // 添加该邮件的主题
    $mail->Subject = 'OA系统有新的来文，请登陆查阅或批示。';
    // 添加邮件正文
    $mail->Body = $content;

    if(is_array($files) && count($files)>0 ){
        foreach ($files as $key => $v) {
            $mail->AddAttachment($v); // 添加附件,并指定名称
        }
    }else{
        if($files !=''){
            $mail->AddAttachment($files); // 添加附件,并指定名称
        }
    }



    //Replace the plain text body with one created manually
    $mail->AltBody = 'This is a plain-text message body';


    //send the message, check for errors
    if (!$mail->send()) {
        return $mail->ErrorInfo;
        //echo "Mailer Error: " . $mail->ErrorInfo;
    } else {
        //echo "Message sent!";
        //Section 2: IMAP
        //Uncomment these to save your message in the 'Sent Mail' folder.
        #if (save_mail($mail)) {
        #    echo "Message saved!";
        #}
    }
}

/**
 *+----------------------------------------------------------
 * 字符串截取，支持中文和其他编码
 *+----------------------------------------------------------
 * @static
 * @access public
 *+----------------------------------------------------------
 * @param string $str 需要转换的字符串
 * @param string $length 截取长度
 * @param string $start 开始位置
 * @param string $charset 编码格式
 * @param string $suffix 截断显示字符
 *+----------------------------------------------------------
 * @return string
 *+----------------------------------------------------------
 */
function msubstr($str, $length, $start=0, $charset="utf-8", $suffix=false){
	if(function_exists("mb_substr")){
		$slice=mb_substr($str, $start, $length, $charset);
		if($suffix){
		  	if(mb_strlen($str,'utf-8')>$length){
		    	return $slice."...";
		    }else{
				return $slice;
			}
		}else{
		   	return $slice;
		}
	}elseif(function_exists('iconv_substr')){
		if($suffix){
		   return iconv_substr($str,$start,$length,$charset)."...";
		}else{
		   return iconv_substr($str,$start,$length,$charset);
		}
	}

	$re['utf-8'] = "/[x01-x7f]|[xc2-xdf][x80-xbf]|[xe0-xef][x80-xbf]{2}|[xf0-xff][x80-xbf]{3}/";
	$re['gb2312'] = "/[x01-x7f]|[xb0-xf7][xa0-xfe]/";
	$re['gbk'] = "/[x01-x7f]|[x81-xfe][x40-xfe]/";
	$re['big5'] = "/[x01-x7f]|[x81-xfe]([x40-x7e]|xa1-xfe])/";
	preg_match_all($re[$charset], $str, $match);
	$slice = join("",array_slice($match[0], $start, $length));		 
	if($suffix) {
		if(strlen($slice)>$length){
		 	return $slice."…";
		}else{
		 	return $slice;
		}
	}
	return $slice;
}